package com.chixing.service.impl;

import com.chixing.mapper.CartMapper;
import com.chixing.mapper.ProductMapper;
import com.chixing.pojo.Cart;
import com.chixing.pojo.CartExample;
import com.chixing.pojo.Product;
import com.chixing.service.ShoppingCartService;
import com.chixing.util.ServerResult;
import com.chixing.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
  @Autowired
  private CartMapper cartMapper;
  @Autowired
  private ProductMapper productMapper;


  @Override
  public ServerResult getByCusId(Integer cusId) {

    CartExample cartExample = new CartExample();
    CartExample.Criteria criteria = cartExample.createCriteria();
    criteria.andCustomerIdEqualTo(cusId);


    //封装购物车信息的vo对象
    CartVo cartVo = new CartVo();
    //根据用户id查询购物车信息。
    List<Cart> carts = cartMapper.selectByExample(cartExample);
    System.out.println("service...cart" + carts);
    HashMap<Cart, Product> map = new HashMap<>();
    for (Cart c:carts
         ) {
      Integer productId = c.getProductId();
      Product product = productMapper.selectByPrimaryKey(productId);
      map.put(c,product);
    }
    System.out.println("service---map" + map);

    //设置vo值
    cartVo.setCarts(carts);
    cartVo.setCartProductMap(map);


    if (carts.size() > 0) {
      System.out.println("server--- 查询 用户：" + cusId + "的购物车信息成功！");
      return ServerResult.getSuccess(cartVo);
    }


    return ServerResult.getFail("查询购物车信息失败。");
  }

  @Override
  public ServerResult getByKeyword(String keyWord) {
    return null;
  }

  @Override
  public ServerResult saveCart(Cart cart) {
    CartExample cartExample = new CartExample();
    CartExample.Criteria criteria = cartExample.createCriteria();
    criteria.andCustomerIdEqualTo(cart.getCustomerId()).andProductIdEqualTo(cart.getProductId());

    int rows = 0;
    List<Cart> carts = cartMapper.selectByExample(cartExample);
    //若该商品已在购物车中存在，则修改该商品在数据库中的商品数量
    if (carts.size() == 1) {
      Cart cart1 = carts.get(0);
      cart.setCartId(cart1.getCartId());

      Integer productNumber = cart.getProductNumber();
      cart.setProductNumber(productNumber + cart1.getProductNumber());
      rows = cartMapper.updateByPrimaryKey(cart);

    } else {
      rows = cartMapper.insert(cart);
    }

    if (rows > 0) {
      return ServerResult.getSuccess(rows);
    }
    return ServerResult.getFail(null);

  }

  @Override
  public ServerResult deleteCart(Integer cartId) {

    int i = cartMapper.deleteByPrimaryKey(cartId);
    if (i > 0) return ServerResult.deleteSuccess(i);

    return ServerResult.deleteFail(null);
  }
}
